#include <stdio.h>
#include <stdlib.h>

int main() {
    int n;
    // 输入验证
    printf("请输入奇数阶数: ");
    if (scanf("%d", &n) != 1 || n <= 0 || n % 2 == 0) {
        printf("错误：请输入正奇数\n");
        return 1;
    }
    // 动态分配避免栈溢出
    int** cube = (int**)malloc(n * sizeof(int*));
    if (!cube) {
        printf("内存分配失败\n");
        return 1;
    }
    for (int i = 0; i < n; i++) {
        cube[i] = (int*)calloc(n, sizeof(int));
        if (!cube[i]) {
            printf("内存分配失败\n");
            // 清理已分配内存
            for (int j = 0; j < i; j++) free(cube[j]);
            free(cube);
            return 1;
        }
    }
    // 特殊处理n=1的情况
    if (n == 1) {
        cube[0][0] = 1;
    }
    else {
        // 幻方填充算法
        int i = 0, j = n / 2;
        cube[i][j] = 1;

        for (int k = 2; k <= n * n; k++) {
            int next_i = (i - 1 + n) % n;  // 使用模运算简化边界处理
            int next_j = (j + 1) % n;

            if (cube[next_i][next_j] != 0) {
                next_i = (i + 1) % n;
                next_j = j;
            }

            i = next_i;
            j = next_j;
            cube[i][j] = k;
        }
    }
    // 输出结果
    printf("%d阶幻方:\n", n);
    for (int y = 0; y < n; y++) {
        for (int x = 0; x < n; x++) {
            printf("%4d", cube[y][x]);
        }
        printf("\n");
    }
    // 验证幻和
    int magic_sum = n * (n * n + 1) / 2;
    printf("幻和应为: %d\n", magic_sum);
    // 释放内存
    for (int i = 0; i < n; i++) free(cube[i]);
    free(cube);
    return 0;
}